Skip to content

Raise ImageUploadError from Project.upload() when the API answers a string error - #586

Draft
tonylampada wants to merge 2 commits into
mainfrom
tony/upload-string-error
Draft

tonylampada wants to merge 2 commits into
mainfrom
tony/upload-string-error

Conversation

@tonylampada

@tonylampada tonylampada commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Anyone uploading images with the SDK or roboflow image upload, on the released 1.7.3, gets AttributeError: 'str' object has no attribute 'get' when the upload fails and the API answers {"error": "<text>"}.

By the API's code, errors thrown inside the upload handler (403, 404, 409, 500) and the 503 of an instance that is shutting down answer the string shape. A missing or invalid API key does not: production answers those with the object shape, which the SDK already handles. The upload retry catches ImageUploadError only, so num_retry_uploads never retried the string answers. Found by reading the code; no user report.

POST /dataset/<project>/upload  →  503 {"error": "Instance recycling"}
before: AttributeError: 'str' object has no attribute 'get'
after:  ImageUploadError: Instance recycling   (status_code 503)

What changes:

  • Project.upload() and single_upload() raise ImageUploadError with the API's text and status_code.
  • With num_retry_uploads set, the SDK retries that upload.
  • roboflow image upload <file> prints Error: Instance recycling. The exit code is still 1.
  • upload_dataset() and roboflow image upload <folder> print [ERR] <path> (Instance recycling) for that image and go on, as before.

Tested

  • Unit: the two new tests in tests/test_project.py pass on 4cfa25d and fail with the adapter from main.
  • Suite and lint: 1283 tests OK, make check_code_quality clean.
  • CLI: roboflow image upload on a file and on a folder against mocked HTTP, before and after.
  • Live: production's answer to an upload with no key and with an invalid key.
  • Not run: an upload that gets the string answer, which needs a valid key. That shape comes from the API's code in the private roboflow repo, not from a captured response.
Evidence

All runs on 4cfa25d, from the repo root, after uv venv .venv --python 3.12 && uv pip install --python .venv/bin/python -e ".[dev]". No network.

The two new tests

$ .venv/bin/python -m unittest tests.test_project -k string_error -v
test_upload_raises_upload_image_error_for_a_string_error (tests.test_project.TestProject.test_upload_raises_upload_image_error_for_a_string_error) ... loading Roboflow workspace...
loading Roboflow project...
ok
test_upload_retries_after_a_string_error (tests.test_project.TestProject.test_upload_retries_after_a_string_error) ... loading Roboflow workspace...
loading Roboflow project...
ok

----------------------------------------------------------------------
Ran 2 tests in 0.006s

OK

The same tests with the adapter from the base (9415946). Tracebacks cut to their last frame.

$ git checkout 9415946 -- roboflow/adapters/rfapi.py
$ .venv/bin/python -m unittest tests.test_project -k string_error -v
ERROR: test_upload_raises_upload_image_error_for_a_string_error (tests.test_project.TestProject.test_upload_raises_upload_image_error_for_a_string_error)
  File "roboflow/adapters/rfapi.py", line 784, in upload_image
    if err_msg.get("message"):
       ^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'get'
ERROR: test_upload_retries_after_a_string_error (tests.test_project.TestProject.test_upload_retries_after_a_string_error)
  File "roboflow/adapters/rfapi.py", line 784, in upload_image
    if err_msg.get("message"):
       ^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'get'

Ran 2 tests in 0.007s

FAILED (errors=2)
$ git checkout HEAD -- roboflow/adapters/rfapi.py

Suite and lint. mypy's annotation-unchecked notes cut.

$ .venv/bin/python -m unittest
Ran 1283 tests in 48.689s

OK (skipped=1)
$ . .venv/bin/activate && make check_code_quality
ruff format roboflow --check
79 files already formatted
ruff check roboflow
All checks passed!
mypy roboflow
Success: no issues found in 79 source files

The CLI. Save as cli-proof.py and run .venv/bin/python - < cli-proof.py.

import shutil
import tempfile

import responses
from typer.testing import CliRunner

from roboflow.cli import app
from roboflow.config import API_URL
from tests import PROJECT_NAME, ROBOFLOW_API_KEY, WORKSPACE_NAME, RoboflowTest

RoboflowTest().setUp()  # the suite's fixture: mocks the auth, workspace and project calls
responses.add(responses.POST, f"{API_URL}/dataset/{PROJECT_NAME}/upload", json={"error": "Instance recycling"}, status=503)

folder = tempfile.mkdtemp()
shutil.copy("tests/images/rabbit.JPG", folder)
for path in ("tests/images/rabbit.JPG", folder):
    args = ["--api-key", ROBOFLOW_API_KEY, "--workspace", WORKSPACE_NAME, "image", "upload", path, "-p", PROJECT_NAME]
    result = CliRunner().invoke(app, args)
    print("$ roboflow image upload", "<file>" if path.endswith(".JPG") else "<folder>")
    print(result.output.strip().replace(folder, "<folder>"))
    print("exit code", result.exit_code)

On 4cfa25d (progress bar cut):

$ roboflow image upload <file>
Error: Instance recycling
exit code 1
$ roboflow image upload <folder>
loading Roboflow project...
Uploading to existing project my-workspace/test-project
[ERR] <folder>/rabbit.JPG (Instance recycling)
Imported 1 images from <folder> to test-project
exit code 0

With the adapter from 9415946 (progress bar cut):

$ roboflow image upload <file>
Error: 'str' object has no attribute 'get'
exit code 1
$ roboflow image upload <folder>
loading Roboflow project...
Uploading to existing project my-workspace/test-project
[ERR] <folder>/rabbit.JPG ('str' object has no attribute 'get')
Imported 1 images from <folder> to test-project
exit code 0

What production answers without a valid key (2026-11-24, no key needed). Both are the object shape, not the string shape this PR handles.

$ curl -s -w '\nHTTP %{http_code}\n' -X POST 'https://api.roboflow.com/dataset/some-project/upload?name=x.jpg' --data x
{"error":{"message":"This method requires your API key.","type":"OAuthException","hint":"You may pass a token as `api_key` in the request body or query parameters, or through an `Authorization: Bearer <api_key>` header."}}
HTTP 401
$ curl -s -w '\nHTTP %{http_code}\n' -X POST 'https://api.roboflow.com/dataset/some-project/upload?api_key=invalid_key_for_shape_check&name=x.jpg' --data x
{"error":{"message":"This API key does not exist (or has been revoked).","status":401,"type":"OAuthException","hint":"You may retrieve your API key via the Roboflow Dashboard. Go to Account > Roboflow Keys to retrieve yours."}}
HTTP 401

Deploy

None. It ships with the next PyPI release.

Your calls

  • Not confirmed by Tony: every string-shaped error is retried when the caller passes retries, a 404 too, as the object shape already is. If no: retry only 5xx, in Project.upload_image.

Reviewer guide

None: small fix.

🤖 Generated with Claude Code

tonylampada and others added 2 commits November 24, 2026 00:48
rfapi.upload_image read the message of a non-200 answer with
error.get("message"), which assumes "error" is an object. The API also
answers {"error": "<text>"}, for example a 503 from an instance that is
shutting down. That raised AttributeError, which the upload retry does
not catch, so num_retry_uploads never retried it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@tonylampada

Copy link
Copy Markdown
Collaborator Author

Trail

This change was planned and built by Claude, and reviewed twice by a second model (Codex): once on the plan before any code, once on the diff before this PR opened.

Plan

PLAN
touches   rfapi.upload_image, non-200 body {"error": "<str>"} → raise ImageUploadError(str, status)
touches   Project.upload / single_upload / upload_image → num_retry_uploads retries that answer
touches   Workspace.upload_dataset, `roboflow image upload` → print the API's text; exit 1 kept
touches   CHANGELOG.md → entry under Unreleased / Fixed, with the PR link
tests     upload, API answers 503 {"error": "<str>"} → ImageUploadError, text, 503 · test_project
tests     same answer then 200, num_retry_uploads=2 → uploaded, 1 retry, 2 calls · test_project
review    Actionable error messages — CLI line: user reads the API's text, not an AttributeError
verify    .venv/bin/python -m unittest tests.test_project -k string_error -v → the 2 new tests OK
verify    .venv/bin/python -m unittest; make check_code_quality → OK; staging not run: no key
calls     retry every status once it raises (401/404 too), as {"error": {..}} does — ask: Tony

Reviews

Review Rounds Time Verdict Findings
Plan, before any code 1 66 s go none
Diff, at 4cfa25d 1 48 s go none

No finding in either review, so there is no answer to record.

Notes taken from the plan review (none changed the plan)

  • Production edits stay in the adapter. Project, Workspace and the CLI are affected callers, and their retry, propagation and printing already work with ImageUploadError.
  • "exit 1 kept" is about the single-file roboflow image upload <file>. A folder upload catches each image's error in Workspace.upload_dataset, prints [ERR] <path> (<text>) and returns normally. That stays.
  • The first test asserts the exception text and status_code. The second counts the upload POSTs only, not the fixture's auth requests, and asserts the returned retry count.
  • Retrying 401 and 404 follows what the SDK already does for {"error": {"message": ...}}. It is the open call in the PR body.

Notes taken from the diff review

  • The reviewer did not run the full suite or staging. Its run of tests.test_project tests.test_rfapi had 2 TestUploadConnectionReuse errors because its sandbox cannot open localhost sockets. The full suite in the PR body ran outside that sandbox, 1283 OK.

Seen next to the fix and left out

  • Project.upload_image sets e.retries from a counter it updates only on success, so a failed upload always reports 0 retries and upload_dataset never prints "(with N retries)".
  • The 200 branch of rfapi.upload_image calls .get on any truthy JSON body, and a dict error without message puts a dict in ImageUploadError.message. No caller produces either today.
  • roboflow image upload <folder> prints "Imported 1 images" and exits 0 when the only image failed.
Plan review, round 1

Plan gate review

No Critical or Warning findings. The plan addresses the shared cause in rfapi.upload_image; the proposed exception and retry tests exercise the real broken path.

Evidence

Read CLAUDE.md and traced Project.upload → single_upload → upload_image → rfapi.upload_image, plus Workspace.upload_dataset and both CLI upload handlers.

Ran a mocked HTTP reproduction with the installed worktree .venv/bin/python, responses, and the existing TestProject setup: project.upload('tests/images/rabbit.JPG', num_retry_uploads=2) with a 503 {"error": "Upload temporarily unavailable"} followed by a successful 200 response. Actual: AttributeError: 'str' object has no attribute 'get', one upload POST. Expected after the fix: success, one retry, two upload POSTs. No network used. The adapter matches origin/main.

The existing nested-error test checks compatibility with {"error": {"message": ...}}. The planned first regression should assert exception text and status; the second should count upload POSTs specifically, excluding fixture authentication requests, and assert the returned retry count.

Notes

  • Plan lines 3–4: treat Project, Workspace, and CLI as affected callers, not required edits. Existing retry handling, exception propagation, and error rendering already support ImageUploadError; keep production edits in the adapter unless a test demonstrates otherwise.
  • Plan line 4: clarify that “exit 1 kept” describes single-file CLI uploads. Directory uploads catch per-image errors inside Workspace.upload_dataset and currently return normally; changing that behavior is outside this fix.
  • Plan line 10: retrying 401/404 follows the existing exception-based policy for nested errors; no new status-specific retry policy is needed.
  • Full suite, lint, and staging were not run for this plan-only gate; implementation verification remains as planned.

verdict: go

Diff review, round 1

Diff gate review

Reviewed origin/main...HEAD at 4cfa25d against the supplied plan and repository rules.

Findings

None. No Critical, Warning, or Minor findings.

Review

  • Correctness and errors: the dictionary guard prevents calling .get() on the extracted string while preserving nested-message extraction and the upstream HTTP status. Both local and hosted uploads share this response handling.
  • Architecture and size: one guard at the shared adapter boundary fixes all affected callers without adding helpers or duplicating parsing.
  • Call chain: Project.upload → single_upload → upload_image → Retry → rfapi.upload_image. Existing retry handling now receives ImageUploadError; successful retry counts propagate in the upload result. Workspace.upload_dataset prints e.message; single-file CLI uploads pass str(exc) to output_error, retaining exit 1.
  • Naming and scope: no new production names or unrelated changes. The Unreleased/Fixed changelog entry includes the PR link and describes the behavior accurately.
  • Tests: both new tests traverse the real Project/adapter path with HTTP mocks. They assert text/status and successful retry/result/count, respectively; upload request counting excludes setup authentication calls. Existing nested-error coverage remains intact.

Validation

  • .venv/bin/python -m unittest tests.test_project -k string_error -v: 2 passed.
  • Re-ran those tests after substituting only the upload_image function parsed from git show origin/main:roboflow/adapters/rfapi.py in memory: both failed with the original AttributeError: 'str' object has no attribute 'get'. No repository files changed.
  • .venv/bin/python -m unittest tests.test_project tests.test_rfapi -q: 72 tests executed, 70 passed; 2 existing TestUploadConnectionReuse tests errored during setup because the sandbox disallows creating localhost sockets (PermissionError). These failures occur before exercising the changed code.
  • make check_code_quality with worktree venv and caches redirected to scratch: passed formatting, Ruff, and mypy (79 source files).
  • git diff --check origin/main...HEAD: passed; working tree clean.

Notes

  • Full suite and staging were not run in this review; the targeted broader run has the sandbox limitation documented above.
  • Directory CLI uploads retain their existing per-image catch-and-continue behavior; the plan's exit-1 statement applies to single-file uploads.

verdict: go

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant